package org.jtzc.springaiagent.agent.reflective;

import org.jtzc.springaiagent.agent.BaseAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 * @author wu chuang
 * @description
 */
@Service
public class ReflectiveAgent implements BaseAgent {
    private final BaseAgent primaryAgent;
    private final BaseAgent criticAgent;

    @Autowired
    public ReflectiveAgent(
            @Qualifier("executorAgent") BaseAgent primaryAgent,
            @Qualifier("criticAgent") BaseAgent criticAgent) {

        this.primaryAgent = primaryAgent;
        this.criticAgent = criticAgent;
    }

    @Override
    public AgentResponse execute(AgentRequest request) {
        // 初始响应
        AgentResponse initialResponse = primaryAgent.execute(request);
        System.out.println(initialResponse.content());
        // 反思和批评
        AgentRequest critiqueRequest = new AgentRequest(
                "Please critique the following response to the query: " + request.prompt() +
                        "\nResponse: " + initialResponse.content(),
                request.context()
        );

        AgentResponse critique = criticAgent.execute(critiqueRequest);
        System.out.println(critique.content());
        // 改进响应
        if (critique.content().contains("good") || critique.content().contains("adequate")) {
            return initialResponse;
        } else {
            AgentRequest refinementRequest = new AgentRequest(
                    "Original query: " + request.prompt() +
                            "\nInitial response: " + initialResponse.content() +
                            "\nCritique: " + critique.content() +
                            "\nPlease provide an improved response",
                    request.context()
            );

            return primaryAgent.execute(refinementRequest);
        }
    }
}
